"""Task类 - 表示单个自动化任务"""

import uuid
from typing import Callable, List, Dict, Any, Optional
from enum import Enum

class TaskStatus(Enum):
    """任务状态枚举"""
    PENDING = "待执行"
    RUNNING = "执行中"
    SUCCESS = "成功"
    FAILED = "失败"
    SKIPPED = "跳过"

class Task:
    """自动化任务类，封装任务执行逻辑、依赖关系和状态管理"""
    
    def __init__(self, 
                 name: str,
                 action: Callable,
                 args: List[Any] = None,
                 kwargs: Dict[str, Any] = None,
                 dependencies: List['Task'] = None,
                 timeout: int = None,
                 description: str = "",
                 node_type: str = None,
                 node_params: Dict[str, Any] = None):
        """初始化任务
        
        Args:
            name: 任务名称
            action: 要执行的函数
            args: 位置参数列表
            kwargs: 关键字参数字典
            dependencies: 依赖的其他任务列表
            timeout: 任务超时时间（秒）
            description: 任务描述
            node_type: 节点类型
            node_params: 节点参数
        """
        self.id = str(uuid.uuid4())[:8]
        self.name = name
        self.action = action
        self.args = args or []
        self.kwargs = kwargs or {}
        self.dependencies = dependencies or []
        self.timeout = timeout
        self.description = description
        self.status = TaskStatus.PENDING
        self.result = None
        self.error = None
        self.start_time = None
        self.end_time = None
        self.node_type = node_type
        self.node_params = node_params or {}
    
    def can_execute(self) -> bool:
        """检查任务是否可以执行（所有依赖任务是否已成功完成）
        
        Returns:
            可以执行返回True，否则返回False
        """
        if self.status == TaskStatus.RUNNING:
            return False
            
        # 检查所有依赖任务是否成功
        for dep in self.dependencies:
            if dep.status != TaskStatus.SUCCESS:
                return False
                
        return True
    
    def execute(self) -> Any:
        """执行任务
        
        Returns:
            任务执行结果
            
        Raises:
            执行过程中的任何异常
        """
        if not self.can_execute():
            self.status = TaskStatus.SKIPPED
            raise ValueError(f"任务 {self.name} 无法执行，依赖任务未完成或任务正在执行")
            
        self.status = TaskStatus.RUNNING
        self.start_time = __import__('time').time()
        
        try:
            # 如果设置了超时，使用超时机制执行
            if self.timeout:
                import threading
                import queue
                
                result_queue = queue.Queue()
                error_queue = queue.Queue()
                
                def target():
                    try:
                        result = self.action(*self.args, **self.kwargs)
                        result_queue.put(result)
                    except Exception as e:
                        error_queue.put(e)
                
                thread = threading.Thread(target=target)
                thread.daemon = True
                thread.start()
                thread.join(self.timeout)
                
                if thread.is_alive():
                    self.status = TaskStatus.FAILED
                    raise TimeoutError(f"任务 {self.name} 执行超时")
                
                if not error_queue.empty():
                    raise error_queue.get()
                
                self.result = result_queue.get()
            else:
                # 直接执行
                self.result = self.action(*self.args, **self.kwargs)
            
            self.status = TaskStatus.SUCCESS
            return self.result
            
        except Exception as e:
            self.status = TaskStatus.FAILED
            self.error = str(e)
            raise
        finally:
            self.end_time = __import__('time').time()
    
    def get_execution_time(self) -> Optional[float]:
        """获取任务执行时间
        
        Returns:
            执行时间（秒），如果任务未完成返回None
        """
        if self.start_time and self.end_time:
            return self.end_time - self.start_time
        return None
    
    def to_dict(self) -> Dict[str, Any]:
        """将任务信息转换为字典
        
        Returns:
            任务信息字典
        """
        return {
            "id": self.id,
            "name": self.name,
            "status": self.status.value,
            "description": self.description,
            "dependencies_count": len(self.dependencies),
            "start_time": self.start_time,
            "end_time": self.end_time,
            "execution_time": self.get_execution_time(),
            "error": self.error
        }
    
    def __str__(self) -> str:
        """字符串表示
        
        Returns:
            任务的字符串表示
        """
        return f"Task(name='{self.name}', status='{self.status.value}', id='{self.id}')"
    
    def __repr__(self) -> str:
        return self.__str__()